<template>
<modal-container title="编辑" v-el:modal v-ref:modal class="edit-modal" theme="modal-wrapper">
  <form @submit.prevent @reset.prevent v-el:mform>
    <div class="modal-body form-horizontal">
      <table-modal-view :item="item" :columns-set="columnsSet"></table-modal-view>
      <rule-model v-if="ruleName" :rule-list.sync="ruleList" :rule-name="ruleName" @add-rule="addRule" @remove="remove" @time-rule="timeRule" :txt-date="ruleDate"></rule-model>
    </div>
    <div class="modal-footer">
      <v-button @click="close">关闭</v-button>
      <v-button theme="primary" type="submit">保存</v-button>
    </div>
  </form>
</modal-container>
</template>

<script>
import RuleModel from './rule'
import {
  dateTime
} from 'ui/collections/general.js'
import serialize from 'form-serialize'
import {
  deepClone
} from 'lib/clone.js'
import TableModalView from './table-modal'
export default {
  data: () => ({
    ruleParams: {},
    modList: {},
    ruleName: '',
    ruleList: [],
    mchtIdList: [],
    dishList: [],
    couponList: [],
    branchList: [],
    timeRuleArr: []
  }),
  computed: {
    ruleDate: function() {
      let actBegDate
      let actEndDate
      if (this.item.actBegDate.indexOf('-') === -1) {
        actBegDate = `${this.item.actBegDate.substr(0, 4)}-${this.item.actBegDate.substr(4, 2)}-${this.item.actBegDate.substr(6, 2)}`
      } else {
        actBegDate = this.item.actBegDate
      }
      if (this.item.actEndDate.indexOf('-') === -1) {
        actEndDate = `${this.item.actEndDate.substr(0, 4)}-${this.item.actEndDate.substr(4, 2)}-${this.item.actEndDate.substr(6, 2)}`
      } else {
        actEndDate = this.item.actEndDate
      }
      return (actBegDate + '至' + actEndDate)
    }
  },
  components: {RuleModel, TableModalView},
  props: {
    item: {
      type: Object,
      default: () => {}
    },
    'columns-set': {
      type: Array,
      default: () => []
    },
    'rule-id': {
      type: String,
      default: ''
    }
  },
  watch: {
    item: {
      handler: function(val, oldVal) {
        let time
        if (val.modId) {
          this.modelInfor(val.modId)
        }
        if (val.mchtId) {
          this.queryDish(val.mchtId)
          time = val.actEndDate.split("-").join('')
          this.getCoupons(val.mchtId, time)
        }
        if (val.actEndDate) {
          // this.ruleList = []
          time = val.actEndDate.split("-").join('')
          this.getCoupons(val.mchtId, time)
        }
      },
      deep: true
    },
    ruleList: {
      deep: true,
      handler(value) {
          console.log(this.columnsSet);
        if (value.length > 0) {
          this.columnsSet.forEach(col => {
            if (col.data === 'actBegDate') {
              col.readonly = true
            }
          })
        } else {
          this.columnsSet.forEach(col => {
            if (col.data === 'actBegDate') {
              col.readonly = false
            }
          })
        }
      }
    }
  },
  methods: {
    timeRule (isError, index) {
      this.timeRuleArr[index] = isError
    },
    close() {
      this.$emit('reset-load')
    },
    show() {
      this.$refs.modal.init()
    },
    addRule() {
      let list = deepClone(this.ruleParams);
      this.ruleList.push(list);
    },
    remove(index) {
      this.ruleList.splice(index, 1);
    },
    queryDish(mchtId) {
      this.$post({
        url: "/api/v2" + projectName_Url + `/plat/dishType/querylow/${mchtId}`,
        method: "GET"
      }).then(res => {
        let data = res.content.lowTypeNameList;
        data.forEach(dish => {
          dish.key = dish.typeName
          dish.value = (dish.typeId).toString()
        })
        this.dishList = data
      })
    },
    // 获取规则模块
    async modelInfor(modId) {
      let data = await this.$post({
        url: '/api/v2' + projectName_Url + '/plat/mod/rule/' + modId,
        method: 'GET'
      })
      if (data.content) {
        let ruleList = data.content
        ruleList.conInf.forEach(item => {
          if (item.fldInputMd === '03') {
            item.fldValue = []
          } else if (item.fldDataType === '03') {
            item.fldValue = [
              ['00', '00', '00'],
              ['23', '59', '59']
            ]
          } else {
            item.fldValue = ''
          }
          if (item.fldName === 'fp_type') {
            item.options = this.dishList
          }
        })
        ruleList.conInf.push({
          fldInputMd: '01',
          fldName: ruleList.rsValue,
          fldCname: ruleList.ruleName,
          options: this.couponList,
          fldValue: ''
        })
        this.ruleName = ruleList.ruleName
        this.$set('ruleParams', deepClone(ruleList))
      }
    },
    async getModeler(modType) {
      let data = await this.$post({
        url: '/api/v2' + projectName_Url + `/plat/mod/mod/${modType}`,
        method: 'GET'
      })
      if (data.content) {
        let modList = []
        let list = data.content.modTypeList
        list.forEach(item => {
          let value = {
            key: item.modName,
            value: item.modType
          }
          modList.push(value)
        })
        this.$set('modList', modList)
      }
    },
    async juniorMchtIds(mchtId) {
      let mchtIdList = (await this.$post({
        url: "/api/v2" + projectName_Url + "/plat/mcht/getmchtname/" + mchtId,
        method: "GET"
      })).content
      if (mchtIdList.info) {
        mchtIdList.info.forEach(item => {
          item.key = `${item.mchtId}-${item.mchtName}`
          item.value = `${item.mchtId}`
        })
        this.$set('mchtIdList', mchtIdList.info)
      }
    },
    async getCoupons(mchtId, endTime) {
      let couponList = (await this.$post({
        url: '/api/v2' + projectName_Url + '/plat/mod/querycoupon',
        method: "POST",
        data: {
          mchtId,
          endTime
        }
      })).content
      if (couponList.allCoupon) {
        let list = couponList.allCoupon.map(item => ({
          key: item.name,
          value: item.couponId
        }))
        this.$set("couponList", list)
      }
    },
    async getBranch() {
      let self = this;
      var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
      let data = await self.$post({
        url: '/api/v2' + projectName_Url + '/list/mcht/' + mchtId,
        method: "GET"
      });
      if (data) {
        let branchList = [];
        let list = data.content.info
        list.forEach(key => {
          let json = {
            value: key.value,
            key: key.key
          };
          branchList.push(json);
        });
        self.$set("branchList", branchList);
      }
    }
  },
  async ready() {
    dateTime({
      format: "yyyy-mm-dd",
      minView: "2"
    })
    let self = this;

    let item = self.item
    await self.getBranch()
    await self.getModeler(item.actType)
    // await self.juniorMchtIds(item.mchtId)
    await self.getCoupons(item.mchtId, item.actEndDate)
    await self.queryDish(item.mchtId)
    await self.modelInfor(item.modId)

    self.columnsSet.forEach(item => {
      if (item.data === 'modId') {
        item.options = self.modList
      } else if (item.data === 'mchtId') {
        item.options = self.branchList
      } else if (item.data === 'mchtIds') {
        item.checkboxOptions = self.mchtIdList
      }
    })

    let itemData = deepClone(self.item)

    let actRule;
    if (itemData) {
      // 获取活动详情里添加规则的值
      actRule = JSON.parse(itemData.actRule1)[0].modValue[0].value
    }

    // 存储新的添加规则的数据格式
    let new_actRule = [];
    actRule.forEach((arr, index) => {
      let _index = index
      arr[index].forEach(item => {
        let obj = Object.assign({
          key: String(_index)
        }, item)
        new_actRule.push(obj)
      })
    })

    // 合并规则里的参数的数据格式
    let ruleParams = deepClone(self.ruleParams.conInf);
    let _ruleParamsObj = {}
    ruleParams.forEach(param => {
      let key = param.fldName
      _ruleParamsObj[key] = param
    })

    // 根据fldName合并规则里的参数和值
    let paramValArr = []
    let _ruleParamsKeys = Object.keys(_ruleParamsObj)
    new_actRule.forEach(rule => {
      let value = {}
      if (_ruleParamsObj[rule.fldId]) {
        value = Object.assign(_ruleParamsObj[rule.fldId], rule)
      }
      let obj = deepClone(value)
      paramValArr.push(obj)
    })

    // 把一维数组变对象  变成二维
    let obj = {}
    paramValArr.forEach(item => {
      if (item.fldInputMd === '03') {
        let fldValue = []
        if (item.fldValue.indexOf(',') !== -1) {
          fldValue = item.fldValue.split(',')
        } else if (!Array.isArray(item.fldValue)) {
          if (item.fldValue) {
            fldValue[0] = item.fldValue
          }
        }
        item.fldValue = fldValue
        console.log(fldValue);
      }
      if (item.fldDataType === '03') {
        let fldValue = []
        let time = item.fldValue.split(',')
        fldValue[0] = [time[0].substr(0, 2), time[0].substr(2, 2), time[0].substr(4)]
        fldValue[1] = [time[1].substr(0, 2), time[1].substr(2, 2), time[1].substr(4)]
        item.fldValue = fldValue
      };
      if (obj[item.key]) {
        if (obj[item.key].key === item.key) {
          obj[item.key].conInf.push(item)
        }
      } else {
        obj[item.key] = {
          key: item.key,
          conInf: []
        }
        obj[item.key].conInf.push(item)
      }
    })
    let ruleValueArr = []
    Object.keys(obj).forEach(key => {
      ruleValueArr.push(deepClone(obj[key]))
    })
    self.$set('ruleList', ruleValueArr)

    $(self.$els.mform).validate({
      async submitHandler() {
        var form = self.$els.mform;
        var _data = serialize(form, {
          hash: true,
          disabled: true,
          empty: true
        });

        delete _data.money
				delete _data.txn_time_start
				delete _data.txn_time_end

        if (Array.isArray(_data.mchtIds) && _data.mchtIds.length > 1) {
          _data.mchtIds = _data.mchtIds.join(',')
        } else if (!Array.isArray(_data.mchtIds)) {
          _data.mchtIds = _data.mchtIds
        } else {
          _data.mchtIds = ''
        }

        _data.actBegDate = _data.actBegDate.split('-').join('')
        _data.actEndDate = _data.actEndDate.split('-').join('')
        _data.actId = self.item.actId
        // 获取添加规则的数据
        let actRule = [{
          modValue: [{
            ruleId: '',
            value: []
          }]
        }]
        let arrValue = actRule[0].modValue
        arrValue[0].ruleId = self.ruleParams.ruleId
        console.log(self.ruleParams.ruleId);
        let ruleList = self.ruleList
        // 判断交易时间是否正确
        if (self.timeRuleArr.length > 0) {
          let hasError
          self.timeRuleArr.forEach(isError => {
            if (isError) {
              hasError = true
              return
            }
          })
          if (hasError) {
            return
          }
        }
        for (let i = 0, listLen = ruleList.length; i < listLen; i++) {
          let arr = []
          let ruleItem = ruleList[i].conInf
          for (let z = 0, ruleItemLen = ruleItem.length; z < ruleItemLen; z++) {
            // 判断优惠卷的值是否为空
            if (ruleItem[z].fldName === "coupon") {
              if (!ruleItem[z].fldValue) {
                let data = {
                  title: "提示",
                  content: "优惠券不能为空！"
                }
                Midway.alert(data)
                return
              }
            }
            // 插入交易日期
            if (ruleItem[z].fldName === "txn_date") {
              ruleItem[z].fldValue = `${_data.actBegDate},${_data.actEndDate}`
            }
            if (ruleItem[z].fldName !== "fp_type") {
              if (!ruleItem[z].fldValue || ruleItem[z].fldValue.length === 0) {
                let data = {
                  title: "提示",
                  content: "活动规则每项都是必填！"
                }
                Midway.alert(data)
                return
              }
            }
            if (ruleItem[z].fldValue || ruleItem[z].fldValue.length > 0) {
              let value
              if (ruleItem[z].conFldOpr === '06' && ruleItem[z].fldName !== "txn_date") {
                value = ruleItem[z].fldValue.join(',')
              } else if (ruleItem[z].fldDataType === '03' && ruleItem[z].fldName !== "txn_date") { // 时间类型
                value = ruleItem[z].fldValue[0].join('') + ',' + ruleItem[z].fldValue[1].join('')
              } else if (ruleItem[z].fldInputMd === '03') {  // 多选
                let _fldValue = ruleItem[z].fldValue
                value = _fldValue.length === 1? _fldValue[0]: _fldValue.join(',')
                // console.log(value);
              } else {
                value = ruleItem[z].fldValue
              }
              let rule = {
                "fldId": ruleItem[z].fldName,
                "fldValue": value,
                "conFldOpr": ruleItem[z].conFldOpr
              }
              arr.push(rule)
            }
          }
          arrValue[0].value.push({
            [String(i)]: arr
          })
        }
        if (arrValue[0].value.length === 0) {
          let data = {
            title: "提示",
            content: "活动规则不能为空！"
          }
          Midway.alert(data)
          return
        }
        _data.actRule1 = JSON.stringify(actRule)
        let data = await self.$post({
          url: "/api/v2" + projectName_Url + "/plat/act/" + self.item.mchtId + "/" + self.item.actId,
          data: _data,
          method: "PUT"
        });
        Midway.alert({
          title: "操作提示",
          content: data.errorInfo
        });
        $(self.$els.modal).modal('hide');
        self.$emit('reset-load')
      },
      rules: {
        mchtId: {
          required: true,
          number: true,
          int: true,
          maxlength: 11
        },
        mchtIds: {
          required: true,
        },
        couponNum: {
            required: true,
            digits:true,
            number: true
        },
        actName: {
          required: true,
        },
        actType: {
          required: true,
        },
        actDsc: {
          required: true,
        },
        actBegDate: {
          required: true,
          comparisonBeginDate: ['actBegDate', 'actEndDate']
        },
        actEndDate: {
          required: true,
          comparisonDate: ['actBegDate', 'actEndDate']
        },
        modId: {
          required: true,
        },
        money: {
          intMoney: true
        }
      }
    });
  }
}
</script>

<style lang="css">
  .modal-wrapper {
    width: 720px !important;
  }
</style>
